package com.syh.jn.scm.infrastructure.repository.impl.supplier.base.downstream;

import cn.redscarf.commons.util.bean.ExtBeanUtils;
import cn.redscarf.commons.util.other.ExtStringUtils;
import cn.redscarf.commons.wrapper.Wrapper;
import com.syh.core.ddd.infrastructure.repository.AbstractAggregateRepository;
import com.syh.core.expction.UnexpectedlyException;
import com.syh.jn.scm.domain.supplier.entity.base.downstream.DownstreamPriceTemplate;
import com.syh.jn.scm.domain.supplier.entity.base.downstream.DownstreamPriceTmplDetail;
import com.syh.jn.scm.domain.supplier.repository.base.downstream.DownstreamPriceTemplateRepository;
import com.syh.jn.scm.infrastructure.repository.model.base.downstream.DownstreamPriceTemplateModel;
import com.syh.jn.scm.infrastructure.repository.model.base.downstream.DownstreamPriceTmplDetailModel;
import com.syh.jn.scm.infrastructure.repository.model.base.goods.GoodsCategoryModel;
import com.syh.jn.scm.infrastructure.repository.model.base.goods.GoodsModel;
import com.syh.jn.scm.infrastructure.wrapper.ResolveToHQL;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Repository
public class DownstreamPriceTemplateRepositoryImpl extends AbstractAggregateRepository<DownstreamPriceTemplate, DownstreamPriceTemplateModel, Long> implements DownstreamPriceTemplateRepository {
  /**
   * 删除价格模板以及客户商品报价模板
   *
   * @param downstreamPriceTemplate
   */
  @Override
  public void remove(DownstreamPriceTemplate downstreamPriceTemplate) {
    StringBuffer hql = new StringBuffer();
    hql.append("from DownstreamPriceTmplDetailModel model where model.templateId = ?");
    List<DownstreamPriceTmplDetailModel> itemModel = (List<DownstreamPriceTmplDetailModel>) this.hibernateTemplate.find(hql.toString(), downstreamPriceTemplate.getId());
    itemModel.stream().forEach((item)->{
      this.hibernateTemplate.delete(item);
    });
    super.remove(downstreamPriceTemplate);
  }

  /**
   * 批量增加
   *
   * @param details
   */
  @Override
  public void batchSaveDownstreamPriceTmplDetail(List<DownstreamPriceTmplDetail> details) {
    details.stream().forEach((detail)->{
      DownstreamPriceTmplDetailModel model = new DownstreamPriceTmplDetailModel();
      ExtBeanUtils.copyProperties(detail, model);
      //商品相关
      GoodsModel goodsModel = this.hibernateTemplate.get(GoodsModel.class, detail.getGoodsId());
      model.setGoodsCode(goodsModel.getCode());
      model.setGoodsName(goodsModel.getName());
      model.setCodeBar(goodsModel.getCodeBar());
      model.setUnits(goodsModel.getUnits());
      model.setSpecName(goodsModel.getSpecName());
      //分类相关
      GoodsCategoryModel goodsCategoryModel = this.hibernateTemplate.get(GoodsCategoryModel.class, detail.getCategoryId());
      model.setCategoryCatalogCode(goodsCategoryModel.getCatalogCode());
      model.setCategoryName(goodsCategoryModel.getName());
      this.hibernateTemplate.save(model);
    });
  }

  /**
   * 批量修改
   *
   * @param details
   */
  @Override
  public void batchUpdateDownstreamPriceTmplDetail(List<DownstreamPriceTmplDetail> details) {
    details.stream().forEach((detail)->{
      DownstreamPriceTmplDetailModel model = this.hibernateTemplate.get(DownstreamPriceTmplDetailModel.class, detail.getId());
      ExtBeanUtils.copyProperties(detail, model);
      //商品相关
      GoodsModel goodsModel = this.hibernateTemplate.get(GoodsModel.class, detail.getGoodsId());
      model.setGoodsCode(goodsModel.getCode());
      model.setGoodsName(goodsModel.getName());
      model.setCodeBar(goodsModel.getCodeBar());
      model.setUnits(goodsModel.getUnits());
      model.setSpecName(goodsModel.getSpecName());
      //分类相关
      GoodsCategoryModel goodsCategoryModel = this.hibernateTemplate.get(GoodsCategoryModel.class, detail.getCategoryId());
      model.setCategoryCatalogCode(goodsCategoryModel.getCatalogCode());
      model.setCategoryName(goodsCategoryModel.getName());
    });
  }

  /**
   * 删除
   *
   * @param detail
   */
  @Override
  public void deleteDownstreamPriceTmplDetail(DownstreamPriceTmplDetail detail) {
    DownstreamPriceTmplDetailModel model = this.hibernateTemplate.get(DownstreamPriceTmplDetailModel.class, detail.getId());
    if (model != null) {
      this.hibernateTemplate.delete(model);
    }
  }

  /**
   * 根据quotationId查询客户报价商品
   *
   * @param quotationId
   * @return
   */
  @Override
  public DownstreamPriceTmplDetail getByQuotationId(Long quotationId) {
    try {
      DownstreamPriceTmplDetailModel model = this.hibernateTemplate.get(DownstreamPriceTmplDetailModel.class, quotationId);
      if (model == null) {
        return null;
      }
      DownstreamPriceTmplDetail entity = new DownstreamPriceTmplDetail();
      ExtBeanUtils.copyProperties(model, entity);
      return entity;
    } catch (Exception e) {
      throw new UnexpectedlyException(e);
    }
  }

  @Override
  public List<DownstreamPriceTmplDetail> findQuotationListPage(Wrapper wrapper, Integer startRow, Integer count) {
    ResolveToHQL parse = new ResolveToHQL(wrapper);

    StringBuffer hql = new StringBuffer();
    hql.append("FROM DownstreamPriceTmplDetailModel");
    hql.append(" ");
    hql.append(" WHERE 1=1 ");
    hql.append(parse.resolve());
    getLogger().debug(hql.toString());
    Query query = this.hibernateTemplate.getSessionFactory().getCurrentSession().createQuery(hql.toString());

    if (startRow != null && count != null) {
      query.setFirstResult((startRow - 1) * count);
      query.setMaxResults(count);
    }

    List<DownstreamPriceTmplDetailModel> modelList = query.list();
    if (modelList.isEmpty()) {
      return Collections.emptyList();
    }
    return this.transformDownstreamPriceTmplDetail(modelList);
  }

  @Override
  public int getCount(Wrapper wrapper) {
    ResolveToHQL parse = new ResolveToHQL(wrapper);
    StringBuffer hql = new StringBuffer();
    hql.append("SELECT COUNT(*) FROM ");
    hql.append(" DownstreamPriceTmplDetailModel ");
    hql.append(" ");
    hql.append(" WHERE 1=1 ");
    hql.append(parse.resolve());
    this.getLogger().debug(hql.toString());
    Query query = this.buildQuery(hql);
    return ((Long) query.uniqueResult()).intValue();
  }

  /**
   * 根据商品id和模板id拿到报价商品
   *
   * @param id
   * @param tepId
   * @return
   */
  @Override
  public Boolean getByGoodsId(Long id,Long tepId) {
    StringBuffer hql = new StringBuffer();
    hql.append("from DownstreamPriceTmplDetailModel model where model.goodsId = ? and model.templateId = ?");
    List<DownstreamPriceTmplDetailModel> model = (List<DownstreamPriceTmplDetailModel>) super.hibernateTemplate.find(hql.toString(), id,tepId);
    if(model != null && model.size() > 0){
      return Boolean.FALSE;
    }else{
      return Boolean.TRUE;
    }
  }

  /**
   *  根据参数字段查看是否已经被报价模板引用
   * @param column
   * @param id
   * @return
   */
  @Override
  public boolean downstreamPriceTmplDetailExistsByColumn(String column, Long id) {
    StringBuffer hql = new StringBuffer("SELECT COUNT(*) FROM DownstreamPriceTmplDetailModel where ").append(column).append(" = ").append(id);
    this.getLogger().debug(hql.toString());
    Query query = buildQuery(hql);
    return ((Long) query.uniqueResult()).intValue() > 0;
  }

  /**
   * 数据模型转领域对象
   *
   * @param models
   * @return
   */
  private List<DownstreamPriceTmplDetail> transformDownstreamPriceTmplDetail(List<DownstreamPriceTmplDetailModel> models) {
    List<DownstreamPriceTmplDetail> entityList = new ArrayList<>();
    models.stream().forEach((model)->{
      DownstreamPriceTmplDetail entity = new DownstreamPriceTmplDetail();
      ExtBeanUtils.copyProperties(model, entity);
      entityList.add(entity);
    });
    return entityList;
  }
}
